package com.york.security.filter;

import com.york.security.security.JwtUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description:授权过滤器
 * @Data: 2022/3/22 16:12
 * @Author: yangboxiong
 * @Version
 * @since JDK 1.8
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private JwtUtils jwtUtils;
    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtils jwtUtils, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 内部过滤器
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功的用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if (authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request, response);
    }

    /**
     * 从token获取用户名,从redis获取对应权限列表
     *
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从 header 中 获取 token
        String token = request.getHeader("token");
        if (token != null) {
            //从 token 获取用户名
            String userName = JwtUtils.getUserName(token);
            //从 redis 获取对应权限列表
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            for (String permissionKey : permissionValueList) {
                //满足则授予权限，并添加到集合中
                SimpleGrantedAuthority auto = new SimpleGrantedAuthority(permissionKey);
                authority.add(auto);
            }
            return new UsernamePasswordAuthenticationToken(userName, token, authority);
        }
        return null;
    }
}
